package com.diorsunion.hedge.util;

import com.diorsunion.hedge.web.util.LogUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * Http服务类
 * Created by harley-dog on 2016/4/23.
 */
public final class HttpUtils {
    public static String post(String httpurl,Map<String,String> params) throws URISyntaxException, IOException {
        URI uri = null;
        String s = null;
        try {
            uri = getURI(httpurl,params);
            HttpPost httpPost = new HttpPost(uri);
            s = http(httpPost);
        } catch (Exception e) {
            LogUtil.error(LogUtil.net,"http post error,url:"+httpurl+",param:"+params,e);
        } finally {
            return s;
        }
    }

    public static String get(String httpurl,Map<String,String> params) {
        URI uri = null;
        String s = null;
        try {
            uri = getURI(httpurl,params);
            HttpGet httpGet = new HttpGet(uri);
            s = http(httpGet);
        } catch (Exception e) {
            LogUtil.error(LogUtil.net,"http get error,url:"+httpurl+",param:"+params,e);
        } finally {
            return s;
        }
    }

    private static URI getURI(String httpurl, Map<String,String> params) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(httpurl);
        if(params!=null){
            params.forEach((k,v)->uriBuilder.setParameter(k,v));
        }
        URI uri = uriBuilder.build();
        return uri;
    }

    private static String http(HttpUriRequest request) throws IOException {
        CloseableHttpClient httpclient = HttpClients.custom().build();
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();
            String s = EntityUtils.toString(entity);
            return s;
        }catch (IOException e){
            LogUtil.error(LogUtil.net,"http post error,url:"+request.getURI(),e);
            return null;
        }finally {
            if(response!=null){
                response.close();
            }
            if(httpclient!=null){
                httpclient.close();
            }
        }
    }
}
